﻿#include "stdafx.h"
#include "GameService.h"
#include "../Message/Msg_Game.pb.h"
#include "../Message/Msg_RetCode.pb.h"
#include "../Message/Msg_ID.pb.h"
#include "WatcherClient.h"

CGameService::CGameService(void)
{

}

CGameService::~CGameService(void)
{

}

CGameService* CGameService::GetInstance()
{
    static CGameService _GameService;

    return &_GameService;
}

BOOL CGameService::Init()
{
    CommonFunc::SetCurrentWorkDir("");

    if(!CLog::GetInstance()->Start("LogServer", "log"))
    {
        return FALSE;
    }
    CLog::GetInstance()->LogInfo("---------服务器开始启动--------");
    if(!CConfigFile::GetInstance()->Load("servercfg.ini"))
    {
        CLog::GetInstance()->LogError("配制文件加载失败!");
        return FALSE;
    }

    if (CommonFunc::IsAlreadyRun("LogServer" + CConfigFile::GetInstance()->GetStringValue("areaid")))
    {
        CLog::GetInstance()->LogError("LogServer己经在运行!");
        return FALSE;
    }

    CLog::GetInstance()->SetLogLevel(CConfigFile::GetInstance()->GetIntValue("log_log_level"));

    UINT16 nPort = CConfigFile::GetInstance()->GetRealNetPort("log_svr_port");
    if (nPort <= 0)
    {
        CLog::GetInstance()->LogError("配制文件log_svr_port配制错误!");
        return FALSE;
    }

    INT32  nMaxConn = CConfigFile::GetInstance()->GetIntValue("log_svr_max_con");
    if(!ServiceBase::GetInstance()->StartNetwork(nPort, nMaxConn, this, "127.0.0.1"))
    {
        CLog::GetInstance()->LogError("启动服务失败!");
        return FALSE;
    }

    ERROR_RETURN_FALSE(m_LogMsgHandler.Init(0));

    CLog::GetInstance()->LogHiInfo("---------服务器启动成功!--------");

    return TRUE;
}


BOOL CGameService::OnNewConnect(INT32 nConnID)
{
    CWatcherClient::GetInstance()->OnNewConnect(nConnID);

    return TRUE;
}

BOOL CGameService::OnCloseConnect(INT32 nConnID)
{
    CWatcherClient::GetInstance()->OnCloseConnect(nConnID);

    return TRUE;
}

BOOL CGameService::OnSecondTimer()
{

    return TRUE;
}

BOOL CGameService::DispatchPacket(NetPacket* pNetPacket)
{
    if (CWatcherClient::GetInstance()->DispatchPacket(pNetPacket))
    {
        return TRUE;
    }

    if (m_LogMsgHandler.DispatchPacket(pNetPacket))
    {
        return TRUE;
    }

    return FALSE;
}

BOOL CGameService::Uninit()
{
    CLog::GetInstance()->LogError("==========服务器开始关闭=======================");

    ServiceBase::GetInstance()->StopNetwork();

    google::protobuf::ShutdownProtobufLibrary();

    CLog::GetInstance()->LogError("==========服务器关闭完成=======================");

    return TRUE;
}

BOOL CGameService::Run()
{
    while (CWatcherClient::GetInstance()->IsRun())
    {
        ServiceBase::GetInstance()->Update();

        m_LogMsgHandler.OnUpdate(CommonFunc::GetTickCount());

        ServiceBase::GetInstance()->FixFrameNum(30);
    }

    return TRUE;
}

